#!/usr/bin/lua -f
function usage()
_ALERT([[
usage:

cut - remove sections from each line of files

-b byte list [file]
 or
-f field list [file]
-d delimiter (default is tab)
-s only lines with delimiters

a list is ranges separated by commas, for example:

-3,5,7-9,11-

means the 1st-3rd, 5th, 7th-9th, 11th-last bytes or fields.

]])
end

-- add output-delim once getopts handles long options
-- add -s only delimited
-- replace w/ buffered line out

s=arg[0] while strsub(s,-1)~="/" do s=strsub(s,1,-2) end dofile(s.."common.lua")
opts,narg,myst=getopts({b=1,c=1,f=1,d=1,n=0,s=0,h=0,filesonly=1})
if opts.h then usage() exit(0) end
if     opts.c then lst=opts.c
elseif opts.b then lst=opts.b
elseif opts.f then lst=opts.f f=1 end
if not opts.d then del="\t" else del=opts.d end
if not lst then _ALERT("ERROR\n") exit(-1) end
range={}
bits={}
lesr=0
grtr=1E9
for rangeidx=1,1E9 do
	lstidx=strfind(lst,",")
	if lstidx then
		range[rangeidx]=strsub(lst,1,lstidx-1)
		lst=strsub(lst,lstidx+1,-1)
	else
		range[rangeidx]=lst
		break
	end
end
for a,b in range do
	hyph=strfind(b,"-")
	if strsub(b,1,1)=="-" then lesr=tonumber(strsub(b,2,-1))
	elseif strsub(b,-1)=="-" then grtr=tonumber(strsub(b,1,-2))
	elseif not hyph then
		bits[tonumber(b)]=1
	else
		for x=tonumber(strsub(b,1,hyph-1)),tonumber(strsub(b,hyph+1,-1))
		do
			bits[x]=1
		end
	end
end

function oneFile()
	while 1 do
	L=read() O=""
	if not L then break end
	lim=nil some=nil any=nil fpos=1
		for pos=1,strlen(L) do
			B=strsub(L,pos,pos)
			if not f then
				if pos<=lesr or pos>=grtr or bits[pos] then
					O=O..B
				end
			else
				if B==del then
					fpos=fpos+1
					lim=1
					any=1
				elseif fpos<=lesr or fpos>=grtr or bits[fpos] then
					if lim and some then
						O=O..del
						some=nil
					end
					O=O..B
					some=1
					lim=nil
				end
			end
		end
		if any or not f then
			write(O.."\n")
		elseif f and not opts.s then
			write(L.."\n")
		end
	end
end
if getn(arg)==0 then
	do oneFile() end
else
	for a,b in arg do
		readfrom(b)
		do oneFile() end
	end
end

